package com.qintingfm.bootstrapdownload.controller;

import com.qintingfm.bootstrapdownload.download.DownLoadServer;
import com.qintingfm.bootstrapdownload.exceptions.HttpExceptions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLConnection;

/**
 * @author guliuzhong
 */
@Controller
@RequestMapping("/")
public class DownLoadController {
    DownLoadServer downLoadServer;

    @Autowired
    public void setDownLoadServer(DownLoadServer downLoadServer) {
        this.downLoadServer = downLoadServer;
    }
    @GetMapping("/**")
//    @ResponseBody
    public void   download(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException {
        httpServletResponse.addHeader("content-type",downLoadServer.getMIMEType(httpServletRequest.getRequestURI()));
        try {
            downLoadServer.downRequest(httpServletRequest,httpServletResponse.getOutputStream());
        } catch (HttpExceptions httpExceptions) {
            httpServletResponse.setStatus(httpExceptions.getCode());
            httpServletResponse.getOutputStream().print("No file");
//            httpExceptions.printStackTrace();
        }
//        return "download";
    }
}
